<?php

namespace App\Http\Controllers\Freelancer;

use App\Http\Controllers\Controller;
use App\Http\Requests\Freelancer\LoginByWeixinRequest;
use App\Http\Requests\Freelancer\LoginRequest;
use App\Models\Freelancer;
use App\Models\WechatOpenid;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Services\Sms\SmsSender;
use EasyWeChat;

class AuthController extends Controller
{
    protected SmsSender $smsSender;

    public function __construct(SmsSender $smsSender)
    {
        $this->smsSender = $smsSender;
    }

    /**
     * 微信平台服务器验证回调
     */
    public function verifyToken(Request $request)
    {
        Log::info('request arrived.'); 

        $server = \EasyWeChat::officialAccount()->getServer();

        $server->with(function($message){
            return "欢迎关注 overtrue！";
        });

        return $server->serve();
    }

    /**
     * 发送短信验证码
     */
    public function sendSmsCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone' => 'required|string|regex:/^1[3456789]\d{9}$/',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 1,
                'message' => '手机号格式不正确',
                'data' => null
            ]);
        }

        $phone = $request->phone;

        // 检查发送频率限制（60秒内只能发送一次）
        $cacheKey = "sms_code_limit_{$phone}";
        if (Cache::has($cacheKey)) {
            return response()->json([
                'code' => 1,
                'message' => '发送过于频繁，请稍后再试',
                'data' => null
            ], 429);
        }

        // 生成6位数字验证码
        $code = sprintf('%06d', mt_rand(0, 999999));

        // 将验证码存储到缓存，有效期5分钟
        $codeCacheKey = "sms_code_{$phone}";
        Cache::put($codeCacheKey, $code, 300); // 5分钟

        // 设置发送频率限制，60秒
        Cache::put($cacheKey, true, 60);

        try {
            $sendResult = $this->smsSender->sendLoginCode($phone, $code, 5);

            if (!$sendResult->isSuccess()) {
                Log::warning('发送登录验证码短信失败', [
                    'phone' => $phone,
                    'context' => $sendResult->getContext(),
                    'message' => $sendResult->getMessage(),
                ]);

                return response()->json([
                    'code' => 1,
                    'message' => '验证码发送失败，请稍后再试',
                    'data' => null
                ], 500);
            }

            Log::info('发送登录验证码短信成功', [
                'phone' => $phone,
                'message_id' => $sendResult->getMessageId(),
                'context' => $sendResult->getContext(),
            ]);
        } catch (\Throwable $exception) {
            Log::error('发送登录验证码短信异常', [
                'phone' => $phone,
                'exception' => $exception->getMessage(),
            ]);

            return response()->json([
                'code' => 1,
                'message' => '验证码发送失败，请稍后再试',
                'data' => null
            ], 500);
        }

        return response()->json([
            'code' => 0,
            'message' => '验证码发送成功',
            'data' => [
                'phone' => $phone,
                // 仅在测试环境返回验证码
                'test_code' => app()->environment('local', 'testing') ? $code : null
            ]
        ]);
    }

    /**
     * 用户登录
     */
    public function login(LoginRequest $request)
    {
        $validated = $request->validated();
        $phone = $validated['phone'];
        $code = $validated['code'];

        // 验证短信验证码
        $codeCacheKey = "sms_code_{$phone}";
        $cachedCode = Cache::get($codeCacheKey);

        if (!$cachedCode || $cachedCode !== $code) {
            return response()->json([
                'code' => 1,
                'message' => '验证码不正确或已过期',
                'data' => null
            ]);
        }

        try {
            // 查找或创建用户
            $freelancer = Freelancer::firstOrCreate(
                ['phone' => $phone],
                [
                    'name' => '用户' . substr($phone, -4),
                    'status' => 'active',
                    'email' => '',
                    'id_card' => '',
                    'bank_account' => '',
                    'bank_name' => '',
                    'gender' => '',
                    'education' => '',
                    'age' => null,
                    'address' => '',
                    'resume' => '',
                    'verification_status' => Freelancer::VERIFICATION_PENDING,
                    'id_card_recognition_status' => Freelancer::RECOGNITION_PENDING,
                    'face_recognition_status' => Freelancer::RECOGNITION_PENDING,
                ]
            );

            // 清除验证码缓存
            Cache::forget($codeCacheKey);

            // 创建访问令牌
            $token = $freelancer->createToken('freelancer-app')->plainTextToken;

            // 更新最后登录信息（如果字段存在）
            $updateData = [];
            if (Schema::hasColumn('freelancers', 'last_login_at')) {
                $updateData['last_login_at'] = now();
            }
            if (Schema::hasColumn('freelancers', 'last_login_ip')) {
                $updateData['last_login_ip'] = $request->ip();
            }
            if (!empty($updateData)) {
                $freelancer->update($updateData);
            }

            return response()->json([
                'code' => 0,
                'message' => '登录成功',
                'data' => [
                    'token' => $token,
                    'user' => [
                        'id' => $freelancer->id,
                        'phone' => $freelancer->phone,
                        'name' => $freelancer->name,
                        'avatar' => $freelancer->avatar ?? '',
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            Log::info('freelancer login failed', [$e->getFile(),$e->getLine(),$e->getMessage()]);
            return response()->json([
                'code' => 1,
                'message' => '登录失败，请稍后重试',
                'data' => null
            ]);
        }
    }

    /**
     * 微信无感登录
     */
    public function loginByWeixin(LoginByWeixinRequest $request)
    {
        $validated = $request->validated();
        $code = $validated['code'];
        $state = $validated['state'];

        try {
            $officialAccount = EasyWeChat::officialAccount();
            $token = $officialAccount->getOAuth()->tokenFromCode($code);
            $openid = $token['openid'];
        } catch (\Throwable $exception) {
            Log::error('获取微信openid失败', [
                'exception' => $exception->getMessage(),
            ]);

            return response()->json([
                'code' => 1,
                'message' => '微信授权失败，请重试',
                'data' => null,
            ], 400);
        }

        if (! $openid) {
            return response()->json([
                'code' => 1,
                'message' => '未获取到有效的微信标识',
                'data' => null,
            ], 400);
        }

        try {
            $freelancer = DB::transaction(function () use ($openid) {
                $freelancer = Freelancer::where('weixin_openid', $openid)->first();

                if (! $freelancer) {
                    $freelancer = Freelancer::create([
                        'name' => '微信用户' . substr($openid, -4),
                        'phone' => '',
                        'email' => '',
                        'id_card' => '',
                        'address' => '',
                        'resume' => '',
                        'weixin_openid' => $openid,
                        'verification_status' => Freelancer::VERIFICATION_PENDING,
                        'id_card_recognition_status' => Freelancer::RECOGNITION_PENDING,
                        'face_recognition_status' => Freelancer::RECOGNITION_PENDING,
                    ]);
                } elseif ($freelancer->weixin_openid !== $openid) {
                    $freelancer->update(['weixin_openid' => $openid]);
                }

                WechatOpenid::updateOrCreate(
                    ['openid' => $openid],
                    ['freelancer_id' => $freelancer->id]
                );

                return $freelancer;
            });

            $token = $freelancer->createToken('freelancer-app')->plainTextToken;

            $updateData = [];
            if (Schema::hasColumn('freelancers', 'last_login_at')) {
                $updateData['last_login_at'] = now();
            }
            if (Schema::hasColumn('freelancers', 'last_login_ip')) {
                $updateData['last_login_ip'] = $request->ip();
            }
            if (! empty($updateData)) {
                $freelancer->update($updateData);
            }

            return response()->json([
                'code' => 0,
                'message' => '登录成功',
                'data' => [
                    'token' => $token,
                    'user' => [
                        'id' => $freelancer->id,
                        'phone' => $freelancer->phone,
                        'name' => $freelancer->name,
                        'avatar' => $freelancer->avatar ?? '',
                    ],
                ],
            ]);
        } catch (\Throwable $exception) {
            Log::error('微信登录处理失败', [
                'exception' => $exception->getMessage(),
            ]);

            return response()->json([
                'code' => 1,
                'message' => '登录失败，请稍后重试',
                'data' => null,
            ], 500);
        }
    }

    /**
     * 获取当前用户信息
     */
    public function me(Request $request)
    {
        $user = $request->user();

        return response()->json([
            'code' => 0,
            'message' => '获取成功',
            'data' => [
                'user' => [
                    'id' => $user->id,
                    'phone' => $user->phone,
                    'name' => $user->name,
                    'avatar' => $user->avatar ?? '',
                    'status' => $user->status,
                ]
            ]
        ]);
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        try {
            $request->user()->currentAccessToken()->delete();

            return response()->json([
                'code' => 0,
                'message' => '退出登录成功',
                'data' => null
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 1,
                'message' => '退出登录失败',
                'data' => null
            ]);
        }
    }

    /**
     * 注销账号
     */
    public function deleteAccount(Request $request)
    {
        try {
            $user = $request->user();

            // 删除所有令牌
            $user->tokens()->delete();

            // 标记用户为不可用
            $user->update(['status' => 'deleted']);

            return response()->json([
                'code' => 0,
                'message' => '账号注销成功',
                'data' => null
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 1,
                'message' => '账号注销失败，请稍后重试',
                'data' => null
            ]);
        }
    }
}
